package jk.framework.spring.security.cors;

import org.springframework.lang.Nullable;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 动态Url跨域配置源
 * @author cuichao
 */
public class DynamicUrlCorsConfigurationSource implements CorsConfigurationSource {

    private PathMatcher pathMatcher = new AntPathMatcher();

    private UrlPathHelper urlPathHelper = new UrlPathHelper();
    @Nullable
    private String lookupPathAttributeName;

    private CorsConfigurationService configurationService;

    public DynamicUrlCorsConfigurationSource(CorsConfigurationService configurationService){
        super();
        this.configurationService = configurationService;
    }


    private Map<String , CorsConfiguration> loadCorsConfiguration(){
        return configurationService.loadCorsConfiguration();
    }


    @Override
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        String lookupPath = this.urlPathHelper.getLookupPathForRequest(request, this.lookupPathAttributeName);
        for (Map.Entry<String, CorsConfiguration> entry : loadCorsConfiguration().entrySet()) {
            if (this.pathMatcher.match(entry.getKey(), lookupPath)) {
                return entry.getValue();
            }
        }
        return null;
    }


    /**
     * 是否获得fullPath 默认为false
     * @param alwaysUseFullPath
     */
    public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {
        this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath);
    }

    /**
     * 设置url解码
     * @param urlDecode
     */
    public void setUrlDecode(boolean urlDecode) {
        this.urlPathHelper.setUrlDecode(urlDecode);
    }

    /**
     * 设置Servlet-context名称的key
     * @param lookupPathAttributeName
     */
    public void setLookupPathAttributeName(@Nullable String lookupPathAttributeName) {
        this.lookupPathAttributeName = lookupPathAttributeName;
    }

    /**
     * 是否去除url中的分号
     * @param removeSemicolonContent
     */
    public void setRemoveSemicolonContent(boolean removeSemicolonContent) {
        this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent);
    }
}
